<!-- 添加商品类型 -->
<template>
  <el-dialog v-model="dialogVisible" title="添加商品类型" width="30%" :before-close="handleClose">
    <el-form :model="typeForm" label-width="120px">
      <el-form-item label="类型名称" required>
        <el-input v-model="typeForm.typeName" placeholder="请输入商品类型名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="初始库存">
        <el-input-number v-model="typeForm.inventory" :min="0" :precision="0" placeholder="请输入初始库存"></el-input-number>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="typeForm.isDelete" placeholder="请选择状态">
          <el-option label="正常" value="0"></el-option>
          <el-option label="删除" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}
</style>

<script setup>
import { ref, reactive, defineEmits, defineExpose } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['update:modelValue', 'refresh-list'])
const dialogVisible = ref(false)

// 修改表单数据的初始值
const typeForm = reactive({
  typeName: '',
  inventory: 0,
  isDelete: '0'  // 默认为不删除
})

const submitForm = async () => {
  try {
    // 添加表单验证
    if (!typeForm.typeName || typeForm.typeName.trim() === '') {
      ElMessage.error('商品类型名称不能为空')
      return
    }

    // 构造发送的数据
    const payload = {
      typeName: typeForm.typeName.trim(),
      inventory: parseInt(typeForm.inventory) || 0,
      isDelete: parseInt(typeForm.isDelete) || 0
    }


    const response = await axios.post('/addGoodType', payload, {
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    })

    if (response.data.status === 200) {
      ElMessage.success('添加商品类型成功')
      emits('refresh-list')  // 刷新列表
      handleClose()
    } else {
      ElMessage.error(response.data.msg || '添加失败')
    }
  } catch (error) {
   
    ElMessage.error('添加商品类型失败，请稍后重试')
  }
}

const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  typeForm.typeName = ''
  typeForm.inventory = 0
  typeForm.isDelete = '0'
}

// 暴露必要的属性和方法
defineExpose({
  dialogVisible,
  typeForm
})
</script>